package com.wonderful.eyepetizer.data.repo

import android.util.Log
import androidx.compose.runtime.MutableState
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import com.wonderful.eyepetizer.app.BASE_URL
import com.wonderful.eyepetizer.app.ktx.fromJson
import com.wonderful.eyepetizer.app.ktx.toJson
import com.wonderful.eyepetizer.data.db.VideoDao
import com.wonderful.eyepetizer.data.db.VideoEntity
import com.wonderful.eyepetizer.data.entity.bean.BaseApiResult
import com.wonderful.eyepetizer.data.entity.bean.Category
import com.wonderful.eyepetizer.data.entity.bean.Issue
import com.wonderful.eyepetizer.data.entity.bean.Item
import com.wonderful.eyepetizer.data.entity.bean.ItemData
import com.wonderful.eyepetizer.data.entity.bean.NewsItem
import com.wonderful.eyepetizer.data.entity.bean.RecommendItem
import com.wonderful.eyepetizer.data.entity.bean.TabListInfo
import com.wonderful.eyepetizer.data.entity.bean.Topic
import com.wonderful.eyepetizer.data.entity.bean.TopicDetail
import com.wonderful.eyepetizer.data.entity.response.Resource
import com.wonderful.eyepetizer.data.http.ApiService
import com.wonderful.eyepetizer.data.paging.AbsPagingSource
import com.wonderful.eyepetizer.data.paging.DailyPagingSource
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject

/**
 * Desc:
 * @Author: wonderful
 * @Time: 2024/1/23 16:24
 */
class MainRepo @Inject constructor(
    private val apiService: ApiService,
    private val videoDao: VideoDao
) : BaseRepo() {

    private val pageSize = 10

    private val pageConfig = PagingConfig(
        pageSize = pageSize,
        initialLoadSize = pageSize,
        prefetchDistance = 1
    )

    /**
     * 获取 daily
     */
    fun getDaily(
        bannerList: MutableList<Item>,
        refreshing: MutableState<Boolean>
    ): Flow<PagingData<Item>> {
        return Pager(
            config = pageConfig,
            pagingSourceFactory = { DailyPagingSource(apiService, bannerList, refreshing) }
        ).flow
    }


    /**
     * 获取相关 video
     */
    suspend fun getRelateVideoList(videoId: Int): Resource<Issue> = executeHttp {
        apiService.getRelateVideoList(videoId)
    }

    /**
     * 保存 video
     */
    suspend fun saveVideo(itemData: ItemData) {
        runCatching {
            val video = videoDao.getVideo(itemData.id)
            if (video == null) {
                videoDao.save(VideoEntity(itemData.id, toJson(itemData)))
            }
        }
    }


    /**
     * 获取关注列表
     */
    fun getFollowList(refreshing: MutableState<Boolean>): Flow<PagingData<Item>> {
        return Pager(
            config = pageConfig,
            pagingSourceFactory = {
                object : AbsPagingSource<Item>(refreshing) {
                    override suspend fun doLoadPage(pageKey: String?): BaseApiResult<Item> {
                        return if (pageKey.isNullOrEmpty()) {
                            apiService.getFollowList()
                        } else {
                            apiService.getFollowList(pageKey)
                        }
                    }
                }
            }
        ).flow
    }

    /**
     * 获取分类列表
     */
    suspend fun getCategoryList(): Resource<List<Category>> = executeHttp {
        apiService.getCategoryList()
    }

    /**
     * 获取分类详情列表
     */
    fun getCategoryDetailList(
        categoryId: Int,
        refreshing: MutableState<Boolean>
    ): Flow<PagingData<Item>> {
        return Pager(config = pageConfig, pagingSourceFactory = {
            object : AbsPagingSource<Item>(refreshing) {
                override suspend fun doLoadPage(pageKey: String?): BaseApiResult<Item> {
                    return if (pageKey.isNullOrEmpty()) {
                        val url =
                            "${BASE_URL}v4/categories/videoList?id=${categoryId}&udid=d2807c895f0348a180148c9dfa6f2feeac0781b5&deviceModel=Android"
                        Log.e("CategoryDetail", "getCategoryVideoList pageKey=$pageKey")
                        apiService.getCategoryVideoList(url)
                    } else {
                        val url =
                            "${pageKey}&udid=d2807c895f0348a180148c9dfa6f2feeac0781b5&deviceModel=Android"
                        Log.e("CategoryDetail", "getFollowList pageKey=$pageKey")
                        apiService.getFollowList(url)
                    }
                }
            }
        }).flow
    }

    /**
     * 获取 topic 列表
     */
    fun getTopicList(refreshing: MutableState<Boolean>): Flow<PagingData<Topic>> {
        return Pager(config = pageConfig, pagingSourceFactory = {
            object : AbsPagingSource<Topic>(refreshing) {
                override suspend fun doLoadPage(pageKey: String?): BaseApiResult<Topic> {
                    return if (pageKey.isNullOrEmpty()) {
                        apiService.getTopicList()
                    } else {
                        apiService.getTopicList(pageKey)
                    }
                }
            }
        }).flow
    }

    /**
     * 获取 topic 详情
     */
    suspend fun getTopicDetail(topicId: Int): Resource<TopicDetail> = executeHttp {
        apiService.getTopicDetail(topicId)
    }

    /**
     * 获取 news 列表
     */
    fun getNewsList(refreshing: MutableState<Boolean>): Flow<PagingData<NewsItem>> {
        return Pager(
            config = pageConfig,
            pagingSourceFactory = {
                object : AbsPagingSource<NewsItem>(refreshing) {
                    override suspend fun doLoadPage(pageKey: String?): BaseApiResult<NewsItem> {
                        return if (pageKey.isNullOrEmpty()) {
                            apiService.getNewsList()
                        } else {
                            apiService.getNewsList(pageKey)
                        }
                    }
                }
            }
        ).flow
    }

    /**
     * 获取 推荐 列表
     */
    fun getRecommendList(refreshing: MutableState<Boolean>): Flow<PagingData<RecommendItem>> {
        return Pager(
            config = pageConfig,
            pagingSourceFactory = {
                object : AbsPagingSource<RecommendItem>(refreshing) {
                    override suspend fun doLoadPage(pageKey: String?): BaseApiResult<RecommendItem> {

                        return if (pageKey.isNullOrEmpty()) {
                            apiService.getRecommendList().apply {
                                itemList.removeAll { it.type == "horizontalScrollCard" }
                            }
                        } else {
                            apiService.getRecommendList(pageKey).apply {
                                itemList.removeAll { it.type == "horizontalScrollCard" }
                            }
                        }
                    }
                }
            }
        ).flow
    }

    /**
     * 获取 hot tab
     */
    suspend fun getTabList(): Resource<TabListInfo> = executeHttp {
        apiService.getHotTabList()
    }

    /**
     * 获取 hot tab data
     */
    suspend fun getHotTabData(url: String): Resource<Issue> = executeHttp {
        apiService.getHotTabData(url)
    }

    /**
     * 获取历史观看记录
     */
    suspend fun getHistoryWatchList(): List<ItemData> {
        val videos = videoDao.getVideoList()
        return if (videos.isNotEmpty()) {
            videos.map<VideoEntity, ItemData> { fromJson(it.content) }.toList()
        } else {
            emptyList()
        }
    }

    /**
     * 删除某个历史记录
     */
    suspend fun deleteHistoryWatchItem(itemData: ItemData) {
        videoDao.delete(VideoEntity(videoId = itemData.id, toJson(itemData)))
    }
}